<template>
  <div class="checkout-container">
    <el-card class="checkout-card">
      <template #header>
        <div class="card-header">
          <h2>购物车结算</h2>
        </div>
      </template>

      <!-- 商品列表 -->
      <div class="product-list">
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column prop="name" label="商品名称" width="180" />
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="99"
                @change="updateQuantity(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small"
                @click="removeItem(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收货地址 -->
      <div class="address-section">
        <h3>收货地址</h3>
        <el-form :model="addressForm" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="addressForm.receiver" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="addressForm.phone" />
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input type="textarea" v-model="addressForm.detail" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 支付方式 -->
      <div class="payment-section">
        <h3>支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
          <el-radio label="bank">银行卡</el-radio>
        </el-radio-group>
      </div>

      <!-- 订单总计 -->
      <div class="order-summary">
        <div class="summary-item">
          <span>商品总价：</span>
          <span>¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>运费：</span>
          <span>¥{{ shippingFee.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>实付款：</span>
          <span>¥{{ (totalPrice + shippingFee).toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交订单按钮 -->
      <div class="checkout-actions">
        <el-button type="primary" size="large" @click="submitOrder">
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request.js'

const router = useRouter()

// 购物车商品数据
const cartItems = ref([])

// 收货地址表单
const addressForm = ref({
  receiver: '',
  phone: '',
  detail: ''
})

// 支付方式
const paymentMethod = ref('alipay')

// 运费
const shippingFee = ref(10)

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    const user_name = JSON.parse(sessionStorage.getItem('user-name'))
    if (!user_name) {
      ElMessage.error('未获取到用户信息，请重新登录')
      router.push('/login')
      return
    }

    // 从服务器获取购物车数据
    const res = await request.get('shop/searchOrders', {
      params: {
        user_name: user_name,
        pageNum: 1,
        pageSize: 100
      }
    })

    if (res && res.code === 200) {
      const content = res.data?.content || res.data?.data || []
      console.log('购物车数据:', content) // 添加日志
      cartItems.value = content.map(item => ({
        id: item.id,
        name: item.name,
        price: item.price_sum,
        quantity: item.count,
        image: item.image || '/default-medicine.jpg'
      }))
      console.log('处理后的购物车数据:', cartItems.value) // 添加日志
    } else {
      ElMessage.warning('获取购物车数据失败，请稍后重试')
      cartItems.value = []
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.warning('获取购物车数据失败，请稍后重试')
    cartItems.value = []
  }
}

// 更新商品数量
const updateQuantity = async (item) => {
  try {
    const res = await request.put('shop/updateShop', {
      id: item.id,
      count: item.quantity,
      price_sum: item.price * item.quantity
    })

    if (res && res.code === 200) {
      ElMessage.success('数量更新成功')
    } else {
      throw new Error(res?.message || '更新数量失败')
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败，请稍后重试')
  }
}

// 删除商品
const removeItem = async (item) => {
  ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`shop/deleteShopCar/${item.id}`)

      if (res && res.code === 200) {
        const index = cartItems.value.findIndex(i => i.id === item.id)
        if (index > -1) {
          cartItems.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      } else {
        throw new Error(res?.message || '删除商品失败')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败，请稍后重试')
    }
  })
}

// 提交订单
const submitOrder = async () => {
  if (!addressForm.value.receiver || !addressForm.value.phone || !addressForm.value.detail) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  try {
    const user_name = JSON.parse(sessionStorage.getItem('user-name'))
    if (!user_name) {
      ElMessage.error('未获取到用户信息，请重新登录')
      return
    }

    // 为每个商品创建订单
    const orderPromises = cartItems.value.map(async (item) => {
      const orderData = {
        user_name: user_name,
        name: item.name,  // 使用药品名称作为标识
        address: addressForm.value.detail,
        receiver: addressForm.value.receiver,
        phone: addressForm.value.phone,
        price_sum: item.price * item.quantity,
        count: item.quantity,
        create_date: new Date().toISOString(),
        order_status: 0, // 0: 未支付
        payment_method: paymentMethod.value
      }
      return request.post('order/addOrder', orderData)
    })

    // 等待所有订单创建完成
    const results = await Promise.all(orderPromises)
    
    // 检查是否所有订单都创建成功
    const allSuccess = results.every(res => res && res.code === 200)
    
    if (allSuccess) {
      ElMessage.success('订单提交成功')
      // 清空购物车
      await request.delete('shop/deleteBatchOrder', {
        data: cartItems.value.map(item => item.id)
      })
      // 跳转到订单列表页面
      router.push('/tcmmarket')
    } else {
      throw new Error('部分订单提交失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败，请稍后重试')
  }
}

// 页面加载时获取购物车数据
onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.checkout-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.checkout-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-list {
  margin-bottom: 30px;
}

.address-section,
.payment-section {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.order-summary {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 16px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.checkout-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

h3 {
  margin-bottom: 15px;
  color: #303133;
}
</style> 